﻿package com.netease.dylan.test4;

import com.sun.mirror.apt.*;
import com.sun.mirror.declaration.*;

import java.io.*;
import java.util.*;

public class InterfaceExtractorProcessor implements AnnotationProcessor {
	// 注解处理器的工作环境
	private final AnnotationProcessorEnvironment env;
	private List<MethodDeclaration> interfaceMethods = new ArrayList<MethodDeclaration>();

	public InterfaceExtractorProcessor(AnnotationProcessorEnvironment env) {
		this.env = env;
	}

	public void process() {
		// 查询注解处理器环境中的类型声明
		for (TypeDeclaration typeDecl : env.getSpecifiedTypeDeclarations()) {
			// 获取注解
			ExtractInterface annot = typeDecl.getAnnotation(ExtractInterface.class);
			if (annot == null) {
				break;
			}
			// 遍历所有添加注解的方法
			for (MethodDeclaration m : typeDecl.getMethods()) {
				// 方法签名中的访问控制符是public的，且不是静态方法
				if (m.getModifiers().contains(Modifier.PUBLIC) && !(m.getModifiers().contains(Modifier.STATIC))) {
					interfaceMethods.add(m);
				}
			}
			if (interfaceMethods.size() > 0) {
				try {
					PrintWriter writer = env.getFiler().createSourceFile(annot.value());
					writer.println("package " + typeDecl.getPackage().getQualifiedName() + ";");
					writer.println("public interface " + annot.value() + "{");
					// 写方法声明
					for (MethodDeclaration m : interfaceMethods) {
						writer.print(" public");
						writer.print(m.getReturnType() + " ");
						writer.print(m.getSimpleName() + " ");
						int i = 0;
						// 写方法参数列表
						for (ParameterDeclaration parm : m.getParameters()) {
							writer.print(parm.getType() + " " + parm.getSimpleName());
							if (++i < m.getParameters().size()) {
								writer.print(", ");
							}
						}
						writer.println(");");
					}
					writer.println("}");
					writer.close();
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
			}
		}
	}
}
